package com.acxy.weixin.kit;

import com.acxy.ants.common.kit.HttpKit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-11-04
 */
public class AccessToken {

    private final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    private static ConcurrentMap<String, String> token = new ConcurrentHashMap();

    public static String getAccessTokenStr(String appId, String appSecret){
        String accessToken = token.get("access_token");
        //当access_token不存在或者超时, 重新获取
        if(accessToken == null || (System.currentTimeMillis() - Long.valueOf(token.get("expires")) > 7000000)){
            String result = HttpKit.sendGET(access_token_url.replace("APPID", appId).replace("APPSECRET", appSecret));
            JSONObject resp = JSON.parseObject(result);
            if(resp.get("errcode") == null) {
                accessToken = String.valueOf(resp.get("access_token"));
                token.put("access_token", accessToken);
                token.put("expires_in", String.valueOf(resp.get("expires_in")));
                token.put("expires", String.valueOf(System.currentTimeMillis()));
            }else {
                throw new RuntimeException("获取 access_token 失败 >" + resp);
            }
        }
        return accessToken;
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis()+"|"+"1509799199".length());
    }
}
